package cn.good.yan.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 2. 解决 MQ的消息可靠性 -- 配置类
 *
 * @author shengren.yan
 * @create 2024-06-12
 */

@Component
@Slf4j
public class MQAckConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // @PostConstruct 该类被创建完，执行该方法 ，需要把 rabbitTemplate 与ConfirmCallback、ReturnsCallback绑定上
    // this 指定是当前对象 MQAckConfig
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    /**
     * 确认消息是否发送到交换机
     *
     * @param correlationData
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息发送到交换机 - 成功！数据：" + correlationData);
        } else {
            log.info("消息发送到交换机 - 失败！数据：" + correlationData + " 原因：" + cause);
        }
    }

    /**
     * 确认消息是否发送到队列 - 只有发送失败的时候才会调用该方法
     *
     * @param returned
     */
    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.info("消息主体: " + new String(returned.getMessage().getBody()));
        log.info("应答码: " + returned.getReplyCode());
        log.info("描述：" + returned.getReplyText());
        log.info("消息使用的交换器 exchange : " + returned.getExchange());
        log.info("消息使用的路由键 routing : " + returned.getRoutingKey());
    }

}
